import {
  getCustomer,
  getUserInfo,
  getOss,
  AddRes,
  info,
  setStatus,
  getSystemInfo
} from '../../../api/index'
import {
  setDate
} from '../../../api/date'
import {
  workerTimeDetail,
  sendApply
} from '../../../api/worker'
const app = getApp().globalData
import {
  getWeekDate
} from '../../../utils/util'
//import { from } from 'form-data'
//import { from } from 'form-data'
Page({
  data: {
    content: true,
    hiddenn1: false,
    hiddenn2: false,
    netTime: [],
    uinfo: {},
    safearea: app.safeArea,
    userId: 0,
    userName: '',
    deptId: 104,
    deptName: "",
    title: '标题',
    content: '内容',
    phone: '',
    /** 接待日 */
    applyDate: '',
    /**  上午 */
    startTime: '',
    /**  下午 */
    endTime: '',
    applyDateTime: '',
    /** 其他 图片利用*/
    other: '',
    imagesUrl: '',
    noline: {

      deptId: 104,
      deptName: "财政所",
      /** 处理人ID */
      userId: 1,
      /** 工作人员名称 */
      userName: '张三',
      /** 申请人ID ,是否可以关联微信ID*/
      //applyId: 1,
      /** 申请人名称 */
      applyName: '',
      /** 标题 */
      title: '我的咨询标题',
      phone: '',
      /** 内容 */
      content: '我的咨询内容',

      /** 是否线上 */
      isOnline: '0',

      /** 接待日 */
      applyDate: '2022-09-10',

      /** 接待开始时间 上午 */
      startTime: '8:00-11:30',

      /** 接待结束时间  下午 */
      endTime: '13:30-17:00',


      /** 其他 图片利用*/
      // images:'',
      //other: '',
      /** 是否公众 */
      //isShow: 1,


    },
    online: {
      deptId: '',
      deptName: "",
      /** 处理人ID */
      userId: 1,
      /** 工作人员名称 */
      userName: '张三',
      /** 申请人ID ,是否可以关联微信ID*/
      // applyId: 1,
      /** 申请人名称 */
      //applyName: '王小武',
      /** 标题 */
      title: '我的咨询标题',

      /** 内容 */
      content: '我的咨询内容',

      /** 是否线上 */
      isOnline: '1',

      /** 接待日 */
      applyDate: '2022-09-10',

      /** 接待开始时间 */
      startTime: '8:00-11:30',

      /** 接待结束时间 */
      endTime: '13:30-17:00',


      /** 其他 图片利用*/
      images: '图片无',
      //other: '',
      /** 是否公众 */
      //isShow: 1,


    },

    depts: [{
      deptName: '经管站',
      deptId: 1,
    }],
    //uinfo: {},
    bumen: [{
      name: '经管站',
      id: 1,
    }, {
      name: '统计站',
      id: 2
    }],
    bumenIdx: -1,
    piclist: [],
    serverList: [],
    mname: '',
    pid: '',

    kind: 1,

    selIdx: 0,
    selTime: -1,
    showSelTime: false,
  },
  onLoad: function (e) {
    var worker = JSON.parse(e.worker);
    console.log(worker)
    if (worker) {
      this.setData({
        uinfo: worker,
        userId: worker.userId,
        userName: worker.nickName
      })
      this.getData(worker.userId)
      this.setDetps(worker.depts)
    } else {
      this.setData({
        formMark: true
      })
    }

  },
  showSelPop() {
    this.setData({
      showSelTime: true
    })
  },
  subSelTime() {
    console.log(this.data.selIdx, this.data.selTime);
    if (this.data.selIdx > -1 && this.data.selTime > -1) {
      this.setData({
        showSelTime: false,
        applyDateTime: this.data.applyDate + '【' + this.data.startTime + this.data.endTime + "】",
      })
    } else {
      this.setData({
        showSelTime: false,
      })
    }
    
  },
  setSelTimeIdx(e) {
    console.log(e);

    if (!this.data.netTime[this.data.selIdx].isShow) {
      wx.showToast({
        icon: 'none',
        title: '当日暂无排班'
      })
      return
    }


    const {
      idx
    } = e.currentTarget.dataset
    console.log(idx);
    this.setData({
      selTime: idx,
      startTime: idx == 0 ? "08:00 - 11:30" : "",
      endTime: idx == 1 ? "13:30 - 17:00" : "",
    })
  },
  setSelIdx(e) {

    const {
      idx
    } = e.currentTarget.dataset
    if (!this.data.netTime[idx].isShow) {
      wx.showToast({
        icon: 'none',
        title: '当日暂无排班'
      })
      return
    }
    this.setData({
      selIdx: idx,
      applyDate: this.data.netTime[idx].workTime,
    })
    console.log(this.data.netTime[idx]);
    // this.setData({
    //   hiddenn1: this.data.netTime[idx].times[0] == '' ? true : false,
    //   hiddenn2: this.data.netTime[idx].times[1] == '' ? true : false
    // })
    console.log(this.data.applyDate);
  },
  setDetps(depts) {
    this.setData({
      depts: depts
    })
  },
  getData(id) {
    workerTimeDetail(id).then((res) => {
      //console.log(res);
      this.changeTime(res.datas.workerTimes);
    })
  },
  setKinnd(e) {
    this.setData({
      hiddenn1: false,
      hiddenn2: false,
      deptId: 104,
      deptName: "",
      title: '标题',
      content: '内容',
      phone: '',
      /** 接待日 */
      applyDate: '',
      /**  上午 */
      startTime: '',
      /**  下午 */
      endTime: '',
      applyDateTime: '',
      /** 其他 图片利用*/
      other: '',
      selIdx: 0,
      selTime: -1,
      showSelTime: false,
    })
    const {
      kind
    } = e.currentTarget.dataset
    this.setData({
      kind
    })
  },
  preview(e) {
    let cur = e.currentTarget.dataset.cur
    let imgs = e.currentTarget.dataset.obj
    let pics = []
    imgs.forEach((it) => {
      pics.push(it.split('?')[0])
    })
    wx.previewImage({
      urls: pics,
      current: cur.split('?')[0]
    })
  },
  // conInput(e) {
  //   const {
  //     key
  //   } = e.currentTarget.dataset
  //   this.setData({
  //     ['p.' + key]: e.detail.value
  //   })
  // },
  conInput(e) {
    console.log(e);
    const {
      key
    } = e.currentTarget.dataset.key
    this.setData({
      ['noline.' + key]: e.detail.value
    })
  },
  /**笨写输入函数 */
  titleInput(e) {
    this.setData({
      title: e.detail.value
    })
  },
  contentInput(e) {
    this.setData({
      content: e.detail.value
    })
  },
  phoneInput(e) {
    this.setData({
      phone: e.detail.value
    })
  },
  applyNameInput(e) {
    this.setData({
      applyName: e.detail.value
    })
  },

  subData() {
    // 各种表单验证，也可以后端验证
    let msg = ''
    if (!this.data.deptId) {
      msg = '请选择部门'
    }
    if (!this.data.title && !this.data.content) {
      msg = '请描述问题'
    }
    if (!this.data.applyName) {
      msg = '请填写预约人信息'
    }

    if (!(/^(?:(?:\+|00)86)?1[3-9]\d{9}$/.test(this.data.phone))) {
      msg = '请输入合法手机号'
    }
    if (msg) {
      wx.showToast({
        icon: 'none',
        title: msg
      })
      return
    }
    if (this.data.serverList.length != this.data.piclist.length) {
      this.data.piclist.forEach((it, idx) => {
        this.uploadFile(it)
      })

    }
    this.setData({
      imagesUrl: this.data.serverList.join(',')
    })
    console.log(this.data.imagesUrl);
    this.onLineSubmit()
  },
  //点击展示文本
  content: function () {
    // 取反就好
    var value = !this.data.content;
    this.setData({
      content: value
    })
  },

  onLineSubmit() {
    const p = {
      ...this.data.online, //线上
      images: this.data.imagesUrl,
      userId: this.data.userId,
      userName: this.data.userName,
      //-----
      deptId: this.data.deptId,
      deptName: this.data.deptName,

      title: this.data.title,
      content: this.data.content,
      phone: this.data.phone,
      applyName: this.data.applyName,

      applyDate: this.data.applyDate,
      startTime: this.data.startTime,
      endTime: this.data.endTime,
      other: this.data.other,
      //...this.data.noline,//现场
      // imgs: this.data.piclist, // 图片上传完成，替换成网络路径
      // uid: 111, // 办理人员id
      // bumenid: this.data.depts[this.data.bumenIdx],
      // type: '线上咨询'
    }

    //return;
    sendApply(p).then((res) => {
      wx.showToast({
        icon: 'success',
        title: res.message,
      })
      setTimeout(() => {
        wx.navigateBack()
      }, 1500);

    });
    // if(this.data.piclist.length){
    //   wx.showLoading({
    //     title: '上传中...',
    //     mask: true
    //   })
    // }

  },
  /**现场提交 */
  noLineSubmit() {
    let msg = ''
    // if (!(/^(?:(?:\d{3}-)?\d{8}|^(?:\d{4}-)?\d{7,8})(?:-\d+)?$/.test(this.data.phone)) && !(/^(?:(?:\+|00)86)?1[3-9]\d{9}$/.test(this.data.phone))) {
    if (!(/^(?:(?:\+|00)86)?1[3-9]\d{9}$/.test(this.data.phone))) {
      msg = '请输入合法手机号'
    }
    if (!this.data.applyName) {
      msg = '请填写预约人信息'
    }
    if (msg) {
      wx.showToast({
        title: msg,
        icon: 'none'
      })
      return
    }
    const p = {
      ...this.data.noline, //线下
      userId: this.data.userId,
      userName: this.data.userName,
      //-----
      deptId: this.data.deptId,
      deptName: this.data.deptName,

      title: this.data.title,
      content: this.data.content,
      phone: this.data.phone,
      applyName: this.data.applyName,

      applyDate: this.data.applyDate,
      startTime: this.data.startTime,
      endTime: this.data.endTime,
      other: this.data.other,
      //...this.data.noline,//现场
      // imgs: this.data.piclist, // 图片上传完成，替换成网络路径
      // uid: 111, // 办理人员id
      // bumenid: this.data.depts[this.data.bumenIdx],
      // type: '线上咨询'
    }
    // 各种表单验证，也可以后端验证
    console.log('-------');
    console.log(p);
    console.log(JSON.stringify(p));
    console.log('------');
    // if(p.applyName==''||p.title==''||p.content==''){
    //   wx.showToast({
    //     icon: 'error',
    //     title: '信息请填写完整',
    //   })
    //   return;
    // }
    console.log('---satart apply---');
    sendApply(p).then((res) => {
      wx.showToast({
        icon: 'success',
        title: res.message,
      })
      wx.switchTab({
        url: '/pages/index/index'
      })
    });
    // if(this.data.piclist.length){
    //   wx.showLoading({
    //     title: '上传中...',
    //     mask: true
    //   })
    // }
    // if (this.data.serverList.length == this.data.piclist.length) {
    //   this.subData()
    // } else {
    //   this.data.piclist.forEach((it, idx) => {
    //     this.uploadFile(it)
    //   })
    // }
  },
  chooseImage() {
    var _this = this;
    wx.chooseImage({
      count: 3 - this.data.piclist.length, // 默认3
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths
        _this.setData({
          piclist: _this.data.piclist.concat(tempFilePaths)
        })
      }
    })
  },
  uploadFile(it) {
    wx.uploadFile({
      url: app.domain + 'upload',
      filePath: it,
      name: "file",
      header: {
        "Content-Type": "multipart/form-data",
        "token": app.x_tk
      },
      formData: {},
      success: (res) => {
        console.log(res);
        const t = JSON.parse(res.data)
        this.data.serverList.push(t.datas.url)
        // if (this.data.serverList.length == this.data.piclist.length) {
        //   this.subDataForm()
        // }
      }
    })
  },
  delitem(e) {
    let temp = this.data.piclist
    const idx = e.currentTarget.dataset.index
    temp.splice(idx, 1)

    let sss = this.data.serverList
    if (sss.length > idx) {
      sss.splice(idx, 1)
    }
    this.setData({
      piclist: temp,
      serverList: sss
    })
  },
  // subData() {
  //   wx.hideLoading()
  //   if (this.data.toggleSave) {
  //     return
  //   }
  //   this.data.toggleSave = true
  //   setTimeout(() => {
  //     this.data.toggleSave = false
  //   }, 1000);
  //   let p = this.data.p
  //   p.imgs = this.data.serverList.join(',')
  //   AddRes(p).then((res) => {
  //     wx.showToast({
  //       icon: 'success',
  //       title: res.message,
  //     })
  //     this.data.toggleSave = false
  //     if (app.canWrite) {
  //       this.setData({
  //         ['p.sn']: res.datas.sn
  //       })
  //       this.print()
  //       this.data.savePt = false
  //     } else {
  //       setTimeout(() => {
  //         app.isReload = true
  //         wx.navigateBack()
  //       }, 1000);
  //     }
  //   })
  // },
  bindPickerChange(e) {
    this.setData({
      deptId: this.data.depts[e.detail.value].deptId,
      deptName: this.data.depts[e.detail.value].deptName,
    })
  },
  changeTime(netData) {
    let idSet = new Set(netData.map(o => o.workTime));
    let baseTime = setDate()
    console.log('=====生成一周时间======');
    console.log(baseTime);
    let res = baseTime.map(o => ({
      ...o,
      isShow: idSet.has(o.workTime) ? true : false,
      times: idSet.has(o.workTime) ? netData.filter((x) => {
        return x.workTime == o.workTime;
      })[0].times : ["08:00-11:30", "13:30-17:00"]
    }));
    console.log(res);
    this.setData({
      netTime: res
    })
  }
})